package com.ymdx.action;

import com.opensymphony.xwork2.ModelDriven;
import com.ymdx.entity.Course;
import com.ymdx.entity.Reservation;
import com.ymdx.service.CourseService;
import com.ymdx.service.ReservationService;
import com.ymdx.util.ExcelUtil;
import com.ymdx.util.Page;
import com.ymdx.util.tool.BeanCopyUtil;
import com.ymdx.util.tool.Tools;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 预约信息
 * Created by yangliwei on 2017/8/22.
 */
public class ReservationAction extends GenericActionSupport implements ModelDriven<Reservation> {
    private Reservation reservation;

    private Page<Reservation> page;
    private Integer pageSize = 9;
    private Integer pageNo = 1;

    private String headers;//导出时的标题
    private String contents;//导出时的列名
    private static final String FILE_NAME = "学员预约信息";

    @Resource
    private ReservationService reservationService;

    @Resource
    private CourseService courseService;


    /**
     * 预约信息保存
     *
     * @return
     */
    @Action(value = "/reservation/save", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    })})
    public String save() {

        String reservationName = reservation.getReservationName();
        String reservationMobile = reservation.getReservationMobile();
        Long courseId = reservation.getCourseId();
        if (StringUtils.isAnyBlank(reservationName, reservationMobile) || courseId == null) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        if(!Tools.isMobile(reservationMobile)){
            responseTool.setStatus(0);
            responseTool.setCode("user_mobile_error");
            return SUCCESS;
        }
        //判断用户对于一个课程是否重复提交
        Reservation param = new Reservation();
        param.setCourseId(courseId);
        param.setReservationMobile(reservationMobile);
        if (reservationService.getByExample(param).size() > 0) {
            responseTool.setStatus(0);
            responseTool.setCode("reservation_mutil");
            return SUCCESS;
        }

        //判断课程是否存在
        Course course = courseService.getById(Course.class, courseId);
        if (course == null) {
            responseTool.setStatus(0);
            responseTool.setCode("course_not_exist");
            return SUCCESS;
        }

        Reservation saveReservation = new Reservation();
        BeanCopyUtil.copyProperties(reservation, saveReservation, true);
        saveReservation.setCreateTime(new Date());
        saveReservation.setReservationCourse(course.getName());

        reservationService.save(saveReservation);
        responseTool.setStatus(1);
        responseTool.setData(saveReservation);
        return SUCCESS;
    }

    /**
     * 管理员编辑和新建用户报名信息
     */
    @Action(value = "/admin/reservation/save", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message,data\\.id"
    })})
    public String adminSave() {
        Long id = reservation.getId();
        String reservationName = reservation.getReservationName();
        String reservationMobile = reservation.getReservationMobile();
        Long courseId = reservation.getCourseId();
        if (StringUtils.isAnyBlank(reservationName, reservationMobile) || courseId == null) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        Course course = courseService.getById(Course.class, courseId);
        if (course == null) {
            responseTool.setStatus(0);
            responseTool.setCode("course_not_exist");
            return SUCCESS;
        }
        Reservation oldReservation;

        //每次只有在新建报名信息的时候确定课程名称  编辑报名信息时 如果改课程名称改变了，还是显示旧的名称，除非更改可课程ID
        if (id != null) {
            oldReservation = reservationService.getById(Reservation.class, id);
            if (oldReservation.getCourseId() != courseId) {
                oldReservation.setReservationCourse(course.getName());
            }
        } else {
            oldReservation = new Reservation();
            oldReservation.setReservationCourse(course.getName());
            oldReservation.setCreateTime(new Date());
        }

        BeanCopyUtil.copyProperties(reservation, oldReservation, true);
        reservationService.save(oldReservation);
        responseTool.setStatus(1);
        responseTool.setData(oldReservation);
        return SUCCESS;
    }

    /**
     * 预约信息查看
     *
     * @return
     */
    @Action(value = "/admin/reservation/page", results = {@Result(type = JSON, name = SUCCESS, params = {
            "root", "page",
            "includeProperties", "pageNo,pageSize,totalCount,result\\[\\d+\\]\\.id,result\\[\\d+\\]\\.reservationName,result\\[\\d+\\]\\.reservationMobile,result\\[\\d+\\]\\.reservationCourse"
    })})
    public String page() {
        String reservationName = reservation.getReservationName();
        String reservationMobile = reservation.getReservationMobile();
        String reservationCourse = reservation.getReservationCourse();
        Long courseId = reservation.getCourseId();

        Map<String, Object> args = new HashMap<>();
        if (StringUtils.isNotBlank(reservationName)) {
            args.put("reservationName", reservationName);
        }
        if (StringUtils.isNotBlank(reservationMobile)) {
            args.put("reservationMobile", reservationMobile);
        }
        if (StringUtils.isNotBlank(reservationCourse)) {
            args.put("reservationCourse", reservationCourse);
        }
        if (courseId != null) {
            args.put("courseId", courseId);
        }
        if (page == null) {
            page = new Page<>();
            page.setPageNo(pageNo);
            page.setPageSize(pageSize);
        }
        reservationService.page(page, args);
        responseTool.setStatus(1);
        responseTool.setData(page);
//        System.out.println(page.getResult().size());
        return SUCCESS;
    }


    /**
     * 导出excel
     *
     * @return
     */
    @Action(value = "/admin/reservation/export", results = {@Result(name = SUCCESS, type = JSON, params = {"root", "responseTool"})})
    public String exportReservation() {



/*        ServletOutputStream out;
        //获取网络输出流
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            log.error("打开excel失败", e);
            return ERROR;
        }

        Workbook wb = new HSSFWorkbook();
        response.reset();// 清除首部的空白行
        response.setHeader("Content-disposition", "attachment;filename=" + "filename" + ".xls");
        response.setContentType("application/msexcel");
        try {
            wb.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //这里需要传null 不然出现 java.lang.IllegalStateException: getOutputStream() has already been called for this response
        return null;*/

        ServletOutputStream out;
        //获取网络输出流
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            log.error("打开excel失败", e);
            return ERROR;
        }
        String[] header = headers.split(",");
        String[] params = contents.split(",");
        if (page == null) {
            page = new Page();
        }
        Workbook wb = new HSSFWorkbook();
        Sheet[] sheet = new Sheet[1];
        int temp = 1;
        int rowNum = 0;
        do {
            page.setPageNo(temp);
            page.setPageSize(ExcelUtil.EVERY_EXPORT_ROWS);
            page();
            ExcelUtil.write2workbook(wb, sheet, page, rowNum, params, header);
        } while (page.getTotalCount() > page.getPageNo() * page.getPageSize());

        ExcelUtil.createFileName(FILE_NAME,response);
        response.reset();// 清除首部的空白行
        response.setHeader("Content-disposition", "attachment;filename=" + "filename" + ".xls");
        response.setContentType("application/msexcel");
        try {
            wb.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //这里需要传null 不然出现 java.lang.IllegalStateException: getOutputStream() has already been called for this response
        return null;
    }

    @Override
    public Reservation getModel() {
        if (reservation == null) {
            reservation = new Reservation();
        }
        return reservation;
    }

    public Page<Reservation> getPage() {
        return page;
    }

    public void setPage(Page<Reservation> page) {
        this.page = page;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getPageNo() {
        return pageNo;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }

    public String getHeaders() {
        return headers;
    }

    public void setHeaders(String headers) {
        this.headers = headers;
    }

    public String getContents() {
        return contents;
    }

    public void setContents(String contents) {
        this.contents = contents;
    }
}
